<?php

/**
 * @desc 会員ログイン
 * 
 * create: zhouguoyan
 * update: 2012-03-02 ツバサ（エスワイシステム）
 **/
class MemberLoginController extends AppController {
	var $name = 'MemberLogin';
	
	var $uses = array(
		'Member', 'MailJob', 'CompanyAccount','MemberEmailMsg','MemberEducation','MemberExpWorktype','MemberResume','MemberWork'
	);
	
	/**
	 * @author zhouguoyan
	 * @desc 会员登出
	 **/
	function login_out() {
		$this->Session->delete('member_email_msg');
		$this->Session->delete('login_id');
		$this->rdAuth->logout();
		$this->delCookie("member_cookie");
		$this->redirect("/top/index");
	}

	/**
	 * @author zhouguoyan
	 * @desc 会员登陆
	 **/
	function login() {
		$this->pageTitle = "カモメ中国転職：個人会員ログイン";
		$start_page = '/top/index';
		$redirect = (!empty($this->params['pass'])) ? '/' . join('/', $this->params['pass']) : $start_page; //set redirect path
		

		if(isset($this->rdAuth->id)) {
			$this->redirect($redirect);
		}
		if(isset($_COOKIE['member_cookie'])) {
			$cookie = $_COOKIE['member_cookie'];
			$pwd = substr($cookie, 0, 32);
			$id = substr($cookie, 32);
			$data = $this->CompanyAccount->find("\"CompanyAccount\".\"id\" = '" . $id . "'" . " AND \"CompanyAccount\".\"deleted\" is null" . " AND \"CompanyAccount\".\"login_pwd\" = '" . $pwd . "'");
			if(!empty($data)) {
				$this->rdAuth->set($data['CompanyAccount']);
				$this->redirect($redirect);
			}
		}
		$this->Session->write('login_redirect', $redirect);
	}

	/**
	 * @author zhouguoyan
	 * @desc 会员退会
	 **/
	function withdraw() {
		$this->pageTitle = "カモメ中国転職：退会申し込み";
		$this->data['Member']['withdraw_agree'] = 2;
	}

	/**
	 * @author zhouguoyan
	 * @desc 会员退会确认,保存数据库
	 **/
	function dowithdraw() {
		
		if($this->params['data']['Member']['withdraw_agree'] == 1) {
			
			$id = $this->rdAuth->id;
			$data = $this->Member->find("\"Member\".\"id\"='" . $id . "' and \"Member\".\"deleted\" is null");
			$data['withdraw_reason'] = $this->params['data']['Member']['withdraw_reason'];
			$data['email'] = 'admin@localhost:82';
			
			$contents = $this->getMailTemplate("member_withdraw", $data);
			$subject = $this->Prop->getValue('config.mail_title.member_withdraw');
			
			if($id) {
				$this->Member->del($id, false);
				
				//@author wangyuhua 2012/4/18 start
				$meSql = "delete from member_education_info where member_id = ".Sanitize::sql($id);
				$mewiSql = "delete from member_exp_worktype_info where member_id = ".Sanitize::sql($id);
				$mriSql = "delete from member_resume_info where member_id = ".Sanitize::sql($id);
				$mwiSql = "delete from member_work_info where member_id = ".Sanitize::sql($id);
				$candidateInnerSql = "update candidate_list_inner set deleted =now() where member_id = ".Sanitize::sql($id);
				$this->MemberEducation->query($meSql);
				$this->MemberExpWorktype->query($mewiSql);
				$this->MemberResume->query($mriSql);
				$this->MemberWork->query($mwiSql);
				$this->Member->query($candidateInnerSql);
				//@author wangyuhua 2012/4/18 end
				
				$this->MailJob->saveMsg('web@localhost:82', $data['email'], $subject, $contents);
			}
			$this->rdAuth->logout();
			$this->redirect('/memberLogin/finish');
		
		}else {
			$this->set('message', $this->Valid->tagErrorMsg('isChoose', 'Member/withdraw_agree'));
			$this->render('withdraw');
		}
	}

	function finish() {
	
	}
	
	/**
	 * ログイン処理
	 *
	 * create: zhouguoyan
	 * updata: 2012-03-02 ツバサ（エスワイシステム）
	 **/
	function login_confirm() {
		$this->pageTitle = "カモメ中国転職：個人会員ログイン";
		$redirect = $this->Session->read('login_redirect');
		$message = $this->Member->Login_Valid($this->Valid, $this->params['data']);
		$username = Sanitize::sql($this->params['data']['Member']['login_id']);
		$pwd = md5($this->params['data']['Member']['login_pwd']);
		$this->loginException($message, $message != null);
		//アカウントをチエックする
		$this->Member->belongsTo = array();
		$check_name = $this->Member->find("\"Member\".\"login_id\" = '" . $username . "'" . " AND \"Member\".\"member_role\" = 'member'" . " AND \"Member\".\"deleted\" is null");
		$this->loginException($this->Valid->tagErrorMsg('name01_incorrect', 'Member/login_id'), $check_name['Member']['login_id'] == null && $username != null);
		//アカウントがロックされたかどうかをチエックする
		$missTimes = $check_name['Member']['last_miss_login_time'];
		$id = $check_name['Member']['id'];
		$message = $this->accountIsLock($missTimes);
		$this->loginException($message, $message != null);
		//パスワードをチェックする
		$condition = "\"Member\".\"login_id\" = '" . $username . "'" . " AND \"Member\".\"login_pwd\" = '" . $pwd . "' AND \"Member\".\"deleted\" is null";
		$check_pwd = $this->Member->find($condition);
		if($check_pwd['Member']['id']) {
			//ログイン後に新しいセッションIDを発行します。
			session_regenerate_id();
			
			$this->Member->updateMissLoginTime($id);
			// wang.wei add 2012/4/7 start
			$this->setPwdCheckFlg($this->params['data']['Member']['login_pwd'], $check_pwd);
			// wang.wei add 2012/4/7 end
			$this->loginOk($username, $pwd, $redirect);
		} else { //パスワードが間違いってる場合
			$this->setLastMissLoginTime($id, $missTimes);
			$this->loginException($this->Valid->tagErrorMsg('pwd01_incorrect', 'Member/login_pwd'));
		}
	}
	
	/**
	 * MissLoginTimeをヌルにする
	 *
	 * create:2012-03-0２ ツバサ（エスワイシステム）
	 * updata:2012-03-10 ツバサ（エスワイシステム）
	 * */
	private function missLoginTimeClear($id) {
		$data = array('id'=>$id, 'last_miss_login_time'=>null);
		$this->Member->save($data);
	}
	
	/**
	 * MissLoginTimeをセットする
	 *
	 * create:2012-03-01 ツバサ（エスワイシステム）
	 * updata:2012-03-10 ツバサ（エスワイシステム）
	 * */
	private function setLastMissLoginTime($id, $missTimes = null) {
		$canTry = $this->Prop->getValue('config.login_can_try');
		$subLength = $this->Prop->getValue('config.sub_length');
		$strlen = strlen($missTimes);
		$maxlen = ($canTry - 1) * $subLength;
		if($strlen > $maxlen) {
			$subidx = $strlen - $maxlen;
			$missTimes = substr($missTimes, $subidx);
		}
		$missTimes = $missTimes.time();
		$this->Member->updateMissLoginTime($id, $missTimes);
	}
	
	/**
	 * データベースから取得した秒数時間の文字列を１０桁毎に割り切って、
	 * 配列を作成して、アカウントのロックロック状態を判断する
	 * アカウントがロックされた場合、エラメッセージを返す
	 * そうではないとヌルを返す
	 *
	 * create:2012-03-01 ツバサ（エスワイシステム）
	 * updata:
	 * */
	private function accountIsLock($missTimes) {
		$times = array();
		$nowTime = time();
		$trySecond = $this->Prop->getValue('config.login_try_second');
		$canTry = $this->Prop->getValue('config.login_can_try');
		$lockSecond = $this->Prop->getValue('config.login_lock_second');
		$subLength = $this->Prop->getValue('config.sub_length');
		$arylen = strlen($missTimes) / $subLength;
		if($arylen < $canTry) {
			return null;
		}
		for($i = 0; $i < $arylen; $i++) {
			$times[$i] = substr($missTimes, $i*$subLength, $subLength);
		}
		$lastIdx = $arylen - 1;
		$firstIdx = $arylen - $canTry;
		$this->debug_println($times);
		$this->debug_println($times[$lastIdx]);
		$this->debug_println($times[$firstIdx]);
		$this->debug_println($nowTime);
		if($times[$lastIdx] - $times[$firstIdx] < $trySecond
				&& $nowTime - $times[$lastIdx] < $lockSecond) {
			$str1 = $this->Valid->tagErrorMsg('account_is_lock1', 'CompanyAccount/login_id');
			$str2 = (int) ($lockSecond / 60);
			$str3 = $this->Valid->tagErrorMsg('account_is_lock2', 'CompanyAccount/login_id');
			return $str1.$str2.$str3;
		}
		return null;
	}
	
	
	/**
	 * ログイン例外処理
	 *
	 * create: 2012-03-03 ツバサ（エスワイシステム）
	 * update:
	 * */
	private function loginException($message, $bool = true) {
		if($bool) {
			$this->set('message', $message);
			$this->params['data']['Member']['login_pwd'] = '';
			$this->render('login');
			exit();
		}
	}
	
	/**
	 * ログイン成功した場合のみ、このメソッドを呼び出す
	 *
	 * create: 2012-03-03 ツバサ（エスワイシステム）
	 * update:
	 * */
	private function loginOk($username, $pwd, $redirect) {
		$member_id = $this->rdAuth->id;
		if($this->params['data']['Member']['save'] == 1) {
			$str1 = md5($this->data['Member']['login_pwd']);
			$member_cookie_info = $str1 . $this->rdAuth->id;
			$this->set_Cookie("member_cookie", $member_cookie_info, 30);
		}
		
		$data = $this->Member->find("login_id='" . $username . "' AND login_pwd='" . $pwd . "' AND deleted is null ");
		$this->rdAuth->set($data['Member']);
		$info = array();
		$info['Member']['id'] = $this->rdAuth->id;
		$info['Member']['last_login_data'] = date("Y-m-d H:i:s");
		$this->Member->updateLastLogin($info);
		$this->Session->del('login_redirect');
	
		$this->redirect("http://" . str_replace("www.", "", $_SERVER['SERVER_NAME']) . $redirect);
		exit();
	}
	
	/**
	 * ディバッグ用メソッド
	 *
	 * create: 2012-03-05 ツバサ(エスワイシステム)
	 * */
	protected function debug_println($str) {
		if($this->Prop->getValue('config.debug') != 0) {
			if(is_array($str)) {
				print_r($str);
			} else {
				echo $str;
			}
			echo '<br>';
		}
	}
	
	/**
	 * パスワードチェックTYPE
	 *
	 * add 2012/4/6
	 * @author wang.wei
	 * @param loginpwd
	 * @param check_data
	 *
	 **/
	function setPwdCheckFlg($loginpwd, $check_data){

		if(!$this->Member->getCheckLastChangePwdTime($check_data['Member']['id'], $this->Prop->getValue('config.member_pwd_checkyear'))){
			$flagtime = true;
		}else{
			$flagtime = false;
		}
		if(!$this->Valid->password_input_member($loginpwd) || !$this->Valid->minmaxlength($loginpwd,'6-20')){
			$flagpwd = true;
		}else{
			$flagpwd = false;
		}
		
		if($flagtime && $flagpwd){
			$this->Member->updateMemberCon($check_data['Member']['id'], "pwd_check_flg=".Sanitize::sql($this->Prop->getValue('config.password_both')));
		}else if($flagtime){
			$this->Member->updateMemberCon($check_data['Member']['id'], "pwd_check_flg=".Sanitize::sql($this->Prop->getValue('config.password_overtime')));
		}else if($flagpwd){
			$this->Member->updateMemberCon($check_data['Member']['id'], "pwd_check_flg=".Sanitize::sql($this->Prop->getValue('config.password_str_num')));
		}
	
	}
	

}
?>